const db = require("../db")
const { querySql , queryOne }=require("../db")

function getCategoryList(data){//获取分类列表
    const offset = (data.page - 1) * data.limit;
    let bookSql = `select * from fs_category order by updated_at desc`
    bookSql = `${bookSql} limit ${data.limit} offset ${offset}`
    return querySql(bookSql)
}

async function getCategory(data){//查询分类详情
    
    const category = await queryOne(`select * from fs_category where id='${data.id}'`)
    const number = await queryOne(`select count(a.category_id) as article_count, sum(a.reading_number) as read_count from fs_category  c left outer join fs_article  a on c.id = a.category_id where c.id='${category.id}' and a.state='2'  group by c.id  `)
    console.log("吐了aaa",number)
    if(number==null){
        category.read_count = 0
        category.article_count = 0
   }else{
        category.read_count= number.read_count 
        category.article_count= number.article_count 
   }
    return category
}


async function updateLatelyCategory(data){//更新分类浏览
    data.cid = data.id
    delete  data.id
    const collect =  await queryOne(`select * from fs_latelylist  where uid='${data.uid}' and cid='${data.cid}'`)
    if(collect==null){//如果足迹表没有该足迹就添加
        return db.insert(data,'fs_latelylist')
    }else{
        return db.update(data,'fs_latelylist',`where uid='${data.uid}' and cid='${data.cid}'`)
    }
}

function getLatelyList(data){//获取浏览记录
    let bookSql = `select c.*,l.updated_at from fs_latelylist as l join fs_category as c  on l.cid = c.id where uid='${data.uid}' order by l.updated_at desc`
    return querySql(bookSql)
}





module.exports = {
    getCategoryList,
    getCategory,
    updateLatelyCategory,
    getLatelyList
}